<template>
     <transition name="el-message-fade">
         <div
            :class="[
                'el-message',
                type ? `el-message--${ type }` : '',
                center ? 'is-center' : '',
                showClose ? 'is-closable' : '',
            ]"
            :style="positionStyle"
            v-show="visible"
        >
            <i :class="typeClass"></i>
            <slot>
                <p v-if="!dangerouslyUseHTMLString" class="el-message__content">{{ message }}</p>
                <p v-else v-html="message" class="el-message__content"></p>
            </slot>
            <i v-if="showClose" class="el-message__closeBtn el-icon-close" @click="close"></i>
        </div>
     </transition>
</template>

<script>
const typeMap = {
    success: 'success',
    info: 'info',
    warning: 'warning',
    error: 'error'
};

export default {
    data() {
      return {
          visible: false,
          message: '这是一条消息提示',
          duration: 3000,
          showClose: false,
          closed: false,
          type: 'info',
          verticalOffset: 20,
          center: false,
          dangerouslyUseHTMLString: false,

          onClose: null,
      };
    },
    computed: {
        typeClass() {
            return this.type
            ? `el-message__icon el-icon-${ typeMap[this.type] }`
            : '';
        },
        positionStyle() {
            return {
                'top': `${ this.verticalOffset }px`
            };
        }
    },
    watch: {
      closed(newVal) {
        if (newVal) {
          this.visible = false;
        }
      }
    },
    methods: {
        close() {
            this.closed = true;
            if (typeof this.onClose === 'function') {
                this.onClose(this);
            }
        },
        startTimer() {
            if (this.duration > 0) {
                this.timer = setTimeout(() => {
                    if (!this.closed) {
                        this.close();
                    }
                }, this.duration);
            }
        },
    },
    mounted() {
      this.startTimer();
    },
}
</script>